package edu.study.api.common.constraints;

import edu.study.api.common.enums.BaseStrEnum;
import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;

public class EnumValidator implements ConstraintValidator<IsEnum, String> {

    private List<String> valueList;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isNotEmpty(value) && !valueList.contains(value)) {
            return false;
        }
        return true;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void initialize(IsEnum constraintAnnotation) {
        valueList = new ArrayList<String>();
        Class<? extends Enum<?>> enumClass = constraintAnnotation.value();

        Enum[] enumValArr = enumClass.getEnumConstants();

        for (Enum enumVal : enumValArr) {
            if (enumVal instanceof BaseStrEnum) {
                String code = ((BaseStrEnum) enumVal).getCode();
                valueList.add(code);
            } else {
                valueList.add(enumVal.toString());
            }
        }

    }

}
